package com.centaline.androidsalesblog.rx.map;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.orhanobut.logger.Logger;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;

/**
 * 定位
 */
final class BdLocationOnSubscribe implements Observable.OnSubscribe<BDLocation> {

    private final LocationClient locationClient;
    private final boolean userOnce;
    private boolean unSubscribe;

    public BdLocationOnSubscribe(LocationClient locationClient, boolean userOnce) {
        this.locationClient = locationClient;
        this.userOnce = userOnce;
    }

    @Override
    public void call(final Subscriber<? super BDLocation> subscriber) {
        final BDLocationListener bdLocationListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                locationClient.stop();
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onNext(bdLocation);
                }
                if (userOnce)
                    subscriber.onCompleted();
            }
        };

        locationClient.registerLocationListener(bdLocationListener);

        subscriber.add(new Subscription() {
            @Override
            public void unsubscribe() {
                Logger.d("解绑");
                unSubscribe = true;
                locationClient.stop();
                locationClient.unRegisterLocationListener(bdLocationListener);
                subscriber.onCompleted();
            }

            @Override
            public boolean isUnsubscribed() {
                return unSubscribe;
            }
        });
    }

}